﻿using UnityEngine;
using System.Collections;
using NetWork;
using UnityEngine.SceneManagement;
using AssetLoad;

namespace Room
{
    public class RoomTown : RoomBase
    {
        #region define
        public const string ID_GATEWAY_AREA = "area_1";
        public const string ID_PRISON_AREA = "area_12";
        public const string ID_PRISON_NPC = "npc_010";
        #endregion

        private int loadTime = 0;

        public override SceneType GetSceneType()
        {
            return SceneType.TOWN;
        }

        public override ServerType GetServerType()
        {
            return ServerType.town;
        }

        public override void Init()
        {
            base.Init();
            inited = true;
        }

        public override void InitRoomNet()
        {
            netManager = new RoomNetTown();
            netManager.Init(this);
        }

        protected override void Tick()
        {
            netManager.Tick();
            smallMap.Tick();
            viewController.Tick();
            charactorManager.Tick();
            sceneCamera.Set(cameraDelta, new Vector3(cameraAngle, 0, 0), cameraFOV);
        }

        protected override void OnEnter(params object[] param)
        {
            LoadingPanel.Instance.ShowLoading();

            if (!inited)
            {
                Init();
            }
            StartCoroutine(WaitForLoadComplete());
            ManagerController.Instance.cameraTool.SwitchSceneCamera();
            smallMap.ResetData("UI_zhujiemian_ditu_512", 7.0675f, 12.35f,0,4);
        }
        private IEnumerator WaitForLoadComplete()
        {
            if (SceneManager.GetActiveScene().name != SceneName.town)
            {
                yield return StartCoroutine(AssetBundleManager.Instance.LoadSceneAsync(
                SceneName.sceneFolder + SceneName.town, SceneName.town));
            }
            OnLoadComplete();
        }
        private void OnLoadComplete()
        {
            sceneCamera.Set(cameraDelta, new Vector3(cameraAngle, 0, 0), cameraFOV);
            StaticData.cameraRotate = Vector3.zero;
            LoadNPCDataFromTable("town");
            LoadAreaDataFromTable("town");

            netManager.Enter();
            smallMap.ShowMiniMap();

            Story.StoryManager.Instance.OnTownPageClose();
            Story.StoryManager.Instance.OnTownPageOpen();

            CameraTool.Instance.ResetSceneBloomEffect();
        }

        protected override void OnLeave()
        {
            charactorManager.ClearAll();
            netManager.Leave();
            smallMap.HideMiniMap();
        }

        protected override void OnForeground()
        {
            //gameObject.SetActive(true);
            netManager.Resume();
            viewController.Resume();
            uiManager.gameObject.SetActive(true);
            EasyTouchTool.Instance.ShowJoystick();
            
        }
        

        protected override void OnBackground()
        {
            //gameObject.SetActive(false);
            netManager.Pause();
            viewController.Pause();
            uiManager.gameObject.SetActive(false);
            EasyTouchTool.Instance.Hide();
        }
        

        internal new void RoomLoadEnd()
        {
            LoadingPanel.Instance.HideDelay(0.3f);

            charactorManager.GetSelfCharactor();
            
            if (!string.IsNullOrEmpty(StaticData.townNeedFindQuestTarget))
            {
                //TODO 这里有问题。在这个时候执行 NavMesh.CalculatePath()
                //即使返回true，路径里也没有路径点。
                StartCoroutine(ClickCharactor());
            }
            else if (loadTime <= 0)
            {
                ++loadTime;
                if (GuideManager.Instance != null && string.IsNullOrEmpty(GuideManager.Instance.GetRunningGuide()))
                {
                    ShowTenDaySign();
                }
            }
            charactorManager.CreatePrison("prison");

            DataMessageTool.AddMessage(DataMessage.ROOM_SELF_CREATED, this);
        }
        private IEnumerator ClickCharactor()
        {
            yield return null;

            var npcCharactor = Room.RoomManager.currentRoom.charactorManager.GetCharactor(StaticData.townNeedFindQuestTarget);
            if (npcCharactor != null)
            {
                Room.RoomManager.currentRoom.uiManager.ClickCharactor(npcCharactor);
            }

            StaticData.townNeedFindQuestTarget = "";
            
        }
        
        
        public override void OnMainCharactorLoaded(Transform mc)
        {
            base.OnMainCharactorLoaded(mc);
            viewController.SetPlayer(mc);
        }


        public override void PlayerSay(string playerId, string word)
        {
            var charactor = charactorManager.GetCharactor(playerId);
            if (charactor != null)
            {
                charactor.ShowBubble(word);
            }
        }

        public void ShowTenDaySign()
        {
            ProtoBuf.Message.CSLoginRewardInfo msg = new ProtoBuf.Message.CSLoginRewardInfo();
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSLoginRewardInfo, msg, (pack, bSuccess) =>
            {
                if (bSuccess)
                {
                    ProtoBuf.Message.SCLoginRewardInfo _msg = pack.kBody as ProtoBuf.Message.SCLoginRewardInfo;
                    var townPage = UI.PageManager.Instance.currentPage as UI.TownPage;
                    if (townPage)
                        townPage.tenDaySignBtn.SetActive(_msg.isShow == 1);
                    if (_msg.hasReward == 0)
                    {
                        ShowNotice();
                    }
                    else
                    {
                        UI.PageManager.Instance.OpenPage("TenDaySignPage", "");
                        UI.TenDaySignPage page = (UI.TenDaySignPage)UI.PageManager.Instance.GetDictPage("TenDaySignPage");
                        page.UpdateLoginReward(_msg.items);
                    }
                }
            });
        }

        public void ShowNotice()
        {
            if(loadTime <= 1)
            {
                loadTime += 2;
                ProtoBuf.Message.CSNoticeUrl msg = new ProtoBuf.Message.CSNoticeUrl();
                NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSNoticeUrl, msg, (pack, bSuccess) =>
                {
                    if (bSuccess)
                    {
                        ProtoBuf.Message.SCNoticeUrl _msg = pack.kBody as ProtoBuf.Message.SCNoticeUrl;
                        if (!string.IsNullOrEmpty(_msg.noticeUrl) && _msg.noticeUrl != "null")
                        {
                            UI.PageManager.Instance.OpenPage("AnnouncePage", "");
                        }
                    }
                });
            }
        }
    }
}